package com.wans.guli.search.server.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.wans.guli.search.entity.SkuEntity;
import com.wans.guli.search.mapper.SkuEsMapper;
import com.wans.guli.search.server.ProductService;
import com.wans.guli.search.vo.ProductSearchParamVO;
import com.wans.guli.search.vo.ProductSearchRespVO;
import com.wans.guli.search.vo.SkuEsRestVO;
import org.dromara.easyes.core.biz.EsPageInfo;
import org.dromara.easyes.core.conditions.select.LambdaEsQueryChainWrapper;
import org.dromara.easyes.core.core.EsWrappers;
import org.dromara.easyes.core.toolkit.FieldUtils;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.AggregatorFactories;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@SuppressWarnings("all")
public class ProductServiceImpl implements ProductService {


    @Autowired
    private SkuEsMapper skuEsMapper;


    /**
     * 保存商品信息
     *
     * @param skuEsRestVOList 商品信息
     */
    @Override
    public void save(List<SkuEsRestVO> skuEsRestVOList) {
        // 属性拷贝到SkuEntity
        List<SkuEntity> skuEntities = BeanUtil.copyToList(skuEsRestVOList, SkuEntity.class);
        // 设置id
        skuEntities.forEach(skuEntity -> skuEntity.setId(skuEntity.getSkuId()));

        Integer inserted = skuEsMapper.insertBatch(skuEntities);

        // 批量插入数据
    }

    /**
     * 根据参数查询商品信息
     *
     * @param productSearchParamVO 参数
     * @return 商品信息
     */
    // TODO 低版本复杂查询有Bug - 浪费一天时间
    @Override
    public ProductSearchRespVO getSkuInfoBySearchParam(ProductSearchParamVO productSearchParamVO) {


        LambdaEsQueryChainWrapper<SkuEntity> wrapper = EsWrappers.lambdaChainQuery(skuEsMapper);


        // must
        wrapper.must(w -> {
            w.eq(ObjectUtil.isNotEmpty(productSearchParamVO.getCatalog3Id()),
                            SkuEntity::getCatalogId, productSearchParamVO.getCatalog3Id())

                    .match(StrUtil.isNotBlank(productSearchParamVO.getKeyword()),
                            SkuEntity::getSkuTitle, productSearchParamVO.getKeyword())

                    .in(CollUtil.isNotEmpty(productSearchParamVO.getBrandId()),
                            SkuEntity::getBrandId, productSearchParamVO.getBrandId())

                    .nested(CollUtil.isNotEmpty(productSearchParamVO.getAttrs()),
                            FieldUtils.val(SkuEntity::getAttrs), nestedWrapper -> {
                                nestedWrapper.in(FieldUtils.val(SkuEntity::getAttrs) + "." + FieldUtils.val(SkuEntity.Attr::getAttrId), productSearchParamVO.getAttrs());
                            }
                    );
        });

        // filter 筛选
        wrapper.filter(ObjectUtil.isNotEmpty(productSearchParamVO.getHasStock()), filterWrapper -> {
            filterWrapper.eq(FieldUtils.val(SkuEntity::getHasStock), productSearchParamVO.getHasStock() == 1);
            filterWrapper.ge(FieldUtils.val(SkuEntity::getSkuPrice), productSearchParamVO.getSkuPrice().split("_")[0])
                    .le(FieldUtils.val(SkuEntity::getSkuPrice), productSearchParamVO.getSkuPrice().split("_")[1]);
        });


        // 排序
        if (StrUtil.isNotBlank(productSearchParamVO.getSort())) {
            FieldSortBuilder sortBuilder = SortBuilders.fieldSort(productSearchParamVO.getSort());
            wrapper.sort(sortBuilder);
        }

        // 高亮 - 注解
        // @HighLight(preTag = "<b style='color:red'>", postTag = "</b>", mappingField = "highlightContent")


        // 聚合查询
        // 构建品牌聚合查询
/*
        TermsAggregationBuilder termsBrandNameAggregationBuilder = AggregationBuilders.terms(FieldUtils.val(SkuEntity::getBrandName)).field(FieldUtils.val(SkuEntity::getBrandName));
        TermsAggregationBuilder termsBrandImgAggregationBuilder = AggregationBuilders.terms(FieldUtils.val(SkuEntity::getBrandImg)).field(FieldUtils.val(SkuEntity::getBrandImg));
        AggregationBuilder termsBrandAggregationBuilder = AggregationBuilders.terms(FieldUtils.val(SkuEntity::getBrandId)).field(FieldUtils.val(SkuEntity::getBrandId)).subAggregation(termsBrandNameAggregationBuilder).subAggregation(termsBrandImgAggregationBuilder);
*/

        // 构建属性聚合查询
        /*// 构建分类聚合查询
        TermsAggregationBuilder termsCatalogNameAggregationBuilder = AggregationBuilders.terms(FieldUtils.val(SkuEntity::getCatalogName)).field(FieldUtils.val(SkuEntity::getCatalogName));
        TermsAggregationBuilder termsCatalogAggregationBuilder = AggregationBuilders.terms(FieldUtils.val(SkuEntity::getCatalogId)).field(FieldUtils.val(SkuEntity::getCatalogId)).subAggregation(termsCatalogNameAggregationBuilder);

        // 构建内部属性聚合查询
        TermsAggregationBuilder termsAttrNameAggregationBuilder = AggregationBuilders.terms(FieldUtils.val(SkuEntity.Attr::getAttrName)).field(FieldUtils.val(SkuEntity::getAttrs) + "." + FieldUtils.val(SkuEntity.Attr::getAttrName));
        TermsAggregationBuilder termsAttrValuesAggregationBuilder = AggregationBuilders.terms(FieldUtils.val(SkuEntity.Attr::getAttrValue)).field(FieldUtils.val(SkuEntity::getAttrs) + "." + FieldUtils.val(SkuEntity.Attr::getAttrValue));
        TermsAggregationBuilder termsAttrIdAggregationBuilder = AggregationBuilders.terms(FieldUtils.val(SkuEntity.Attr::getAttrId)).field(FieldUtils.val(SkuEntity::getAttrs) + "." + FieldUtils.val(SkuEntity.Attr::getAttrId)).subAggregation(termsAttrNameAggregationBuilder).subAggregation(termsAttrValuesAggregationBuilder);
        NestedAggregationBuilder nestedAggregationBuilder = AggregationBuilders.nested("nest_" + FieldUtils.val(SkuEntity::getAttrs), FieldUtils.val(SkuEntity::getAttrs)).subAggregation(termsAttrIdAggregationBuilder);

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        searchSourceBuilder.aggregation(termsBrandAggregationBuilder);
        AggregatorFactories.Builder builder = searchSourceBuilder.aggregations();
        builder.addAggregator(termsCatalogAggregationBuilder);
        builder.addAggregator(nestedAggregationBuilder);*/


//        wrapper.setSearchSourceBuilder(searchSourceBuilder);
        // 分页
        EsPageInfo<SkuEntity> page = wrapper.page(0, 10);

        page.getList().forEach(skuEntity -> {
            System.out.println(skuEntity.getHighlightContent());
        });

        return null;
    }

}
